package com.atguigu.gmall.flume.interceptor;

import com.atguigu.gmall.flume.utils.JSONUtil;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;

import java.util.Iterator;
import java.util.List;


public class ETLInterceptor implements Interceptor {

    @Override
    public void initialize() {

    }

    @Override
    /**
     * 1.获取body当中的数据并转换成字符串
     * 2.判断字符串是否是一个合法的json，是返回event，不是返回null
     */
    public Event intercept(Event event) {
        //copilot begin
        // 获取body中的数据
        String body = new String(event.getBody(), StandardCharsets.UTF_8);
        // 判断字符串是否是一个合法的json
        if (JSONUtil.isJSONValidate(body)) {
            return event;
        } else {
            return null;
        }
        //copilot end
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        Iterator<Event> eventIterator = list.iterator();
        while (eventIterator.hasNext()) {
            Event event = eventIterator.next();
            if (intercept(event) == null) {
                eventIterator.remove();
            }
        }

        return list;
    }
    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder {

        @Override
        public Interceptor build() {

            return new ETLInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }


}
